package cn.com.ns.jdbc;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import cn.com.ns.util.BeanUtils;

public class JDBCUtil<T> {
	
	public static Connection connection = null;
    public static PreparedStatement preparedStatement = null;
    public static ResultSet resultSet = null;
        
    /**
     * 连接数据库
     * @return
     */
    public static Connection getConnection(){
        String url = "jdbc:mysql://localhost:3306/hk";
        String user = "root";
        String password = "asdf1234";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(url, user, password);
       } catch (SQLException e) {
           e.printStackTrace();
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       }
        return connection;
    }
    /**
     * 关闭资源
     */
    public static void close(){
        try{
            if(connection != null){
               connection.close();
               connection = null;
            }
            if(preparedStatement != null){
                preparedStatement.close();
                preparedStatement = null;
            }
            if(resultSet!= null){
                resultSet.close();
                resultSet = null;
            }
        }catch(SQLException e){
            e.printStackTrace();
        }
        
    }
	
    public static <T> T selectOne(Object t,Class<?> clazz) throws SQLException, InstantiationException, IllegalAccessException{
    	Statement stmt=getConnection().createStatement();
    	Field[] fields = BeanUtils.findDeclaredFields(clazz);
    	String sql = BeanUtils.selectOneSql(t,fields, clazz);
    	ResultSet rs = stmt.executeQuery(sql);
    	
    	ResultSetMetaData rsm = rs.getMetaData();
        int colNumber = rsm.getColumnCount();
        rs.next();
        Object obj = clazz.newInstance();
        for(int i=1;i<=colNumber;i++){
            Object value = rs.getObject(i);
            for(int j = 0;j<fields.length;j++){
                Field f = fields[j];
                if(f.getName().equals(rsm.getColumnName(i))){
                    boolean flag = f.isAccessible();
                    f.setAccessible(true);
                    f.set(obj, value);
                    f.setAccessible(flag);
                    break;
                }
            }
             
        }
        
    	return (T)obj;
    }
}
